package control;

/*
 * Clase encargada de conectar con los servicios y mapear el objeto usuario
 */

import java.util.ArrayList;
import java.util.List;
import java.security.MessageDigest;

import mapping.Sucursal;
import mapping.Usuario;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.util.Log;

import com.example.goatstore.General;

public class ControlUsuario {
	private static String SOAP_ACTION;
	private static String METHOD_NAME;
	private static final String NAMESPACE = "http://servicioUsuario/";
	private static final String URL = General.getIP()+":8080/ServiciosTaller/UsuarioWebService?wsdl";
	
	public static Usuario makeUsuario(SoapObject result){
		long id = Long.parseLong(result.getProperty("id").toString());
		String nombre = result.getProperty("nombre").toString();
		String apellido = result.getProperty("apellido").toString();
		String tipo = result.getProperty("tipo").toString();
		String email = result.getProperty("email").toString();
		String pass = result.getProperty("pass").toString();
		List<Sucursal> sucursales=new ArrayList<Sucursal>();
		int numeroSucursal = Integer.parseInt(result.getProperty("numeroSucursal").toString());
		int radio = Integer.parseInt(result.getProperty("radio").toString());
		Usuario us=new Usuario(id, nombre, apellido, tipo, email, pass, sucursales, numeroSucursal, radio);
		return us;
	}
	public static void setCall(int metodo)
	{
		switch(metodo) 
		{
			case 1:  
			  METHOD_NAME="obtenerUsuarioId";
			  SOAP_ACTION="http://servicioUsuario/obtenerUsuarioId";
			break;
		    case 2:  
			    METHOD_NAME="crearUsuario";
			    SOAP_ACTION="http://servicioUsuario/crearUsuario";
		    break;
		    case 3:  
			    METHOD_NAME="eliminarUsuario";
			    SOAP_ACTION="http://servicioUsuario/eliminarUsuario";  
		    break;
		    case 4:  
			    METHOD_NAME="actualizarUsuario";
			    SOAP_ACTION="http://servicioUsuario/actualizarUsuario";  
		    break;
		    case 5:  
			    METHOD_NAME="actualizarPass";
			    SOAP_ACTION="http://servicioUsuario/actualizarPass";  
		    break;
		    case 6:  
			    METHOD_NAME="validar";
			    SOAP_ACTION="http://servicioUsuario/validar";  
		    break;
		    case 7:  
			    METHOD_NAME="obtenerUsuarioEmail";
			    SOAP_ACTION="http://servicioUsuario/obtenerUsuarioEmail";  
		    break;
	      
		    case 8:  
				METHOD_NAME="listarUsuarioEmpresa";
				SOAP_ACTION="http://servicioUsuario/listarUsuarioEmpresa";  
		    break;
		}
	}
	
	public static Usuario obtenerUsuario(long id)
	{
        setCall(1);
        Usuario us;
        try 
        {
 	       //Creaccion de la Solicitud
 			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
 			request.addProperty("id",id);
 			//Creaccion del Envelope
 			SoapSerializationEnvelope sobre = new SoapSerializationEnvelope(SoapEnvelope.VER11);
 			sobre.dotNet = false;
 			sobre.setOutputSoapObject(request);
 			//Creaccion del transporte
 			HttpTransportSE transporte = new HttpTransportSE(URL);
 			//Llamada
 			transporte.call(SOAP_ACTION, sobre);
 			//Resultado
 			SoapObject resultsRequestSOAP = (SoapObject)sobre.bodyIn;
 			SoapObject object=(SoapObject) resultsRequestSOAP.getProperty(0);
 			us=makeUsuario(object); 
         }catch (Exception e) 
         {
         	us=null;
         }
 		return us;
	}
	
	public static Usuario obtenerUsuarioEmail(String email)
	{
        setCall(7);
        Usuario us;
		try 
		{
	       //Creaccion de la Solicitud
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			request.addProperty("email",email);
			//Creaccion del Envelope
			SoapSerializationEnvelope sobre = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			sobre.dotNet = false;
			sobre.setOutputSoapObject(request);
			//Creaccion del transporte
			HttpTransportSE transporte = new HttpTransportSE(URL);
			//Llamada
			transporte.call(SOAP_ACTION, sobre);
			//Resultado
			SoapObject resultsRequestSOAP = (SoapObject)sobre.bodyIn;
			SoapObject object=(SoapObject) resultsRequestSOAP.getProperty(0);
			us=makeUsuario(object); 
        }catch (Exception e) 
        {
        	us=null;
        }
		return us;
	}
	
	public static String md5(String clear) throws Exception 
	{
	    MessageDigest md = MessageDigest.getInstance("MD5");
	    byte[] b = md.digest(clear.getBytes());
	    int size = b.length;
	    StringBuffer h = new StringBuffer(size);
	    //algoritmo y arreglo md5
	    for (int i = 0; i < size; i++) 
	    {
	        int u = b[i] & 255;
	        if (u < 16) 
	        {
	        	h.append("0" + Integer.toHexString(u));
	        }
	        else 
	        {
	        	h.append(Integer.toHexString(u));
	        }
	    }
	      //clave encriptada
	    return h.toString();
	}
	
	public static boolean validar(String email, String pass)
	{
        setCall(6);
        boolean la;
		try 
		{
	       //Creaccion de la Solicitud
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			request.addProperty("email",email);
			request.addProperty("pass",md5(pass));
			//Creaccion del Envelope
			SoapSerializationEnvelope sobre = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			sobre.dotNet = false;
			sobre.setOutputSoapObject(request);
			//Creaccion del transporte
			HttpTransportSE transporte = new HttpTransportSE(URL);
			//Llamada
			transporte.call(SOAP_ACTION, sobre);
			//Resultado
			SoapObject resultsRequestSOAP = (SoapObject)sobre.bodyIn;
			la = Boolean.parseBoolean(resultsRequestSOAP.getProperty(0).toString());
        }catch (Exception e) 
        {
        	Log.d( "Sliding", "handleHeight: " + e.getLocalizedMessage());
        	la=false;
        }
		return la;
	}
	
	public static boolean crearUsuario(String nombre, String apellido, String email, String pass, String tipo, int numero, int radio){
        setCall(2);
        boolean res;
		try 
		{
	       //Creaccion de la Solicitud
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			request.addProperty("nombre",nombre);
			request.addProperty("apellido",apellido);
			request.addProperty("email",email);
			request.addProperty("pass",md5(pass));
			request.addProperty("numeroSucursal",numero);
			request.addProperty("tipo",tipo);
			request.addProperty("radio",radio);
			//Creaccion del Envelope
			SoapSerializationEnvelope sobre = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			sobre.dotNet = false;
			sobre.setOutputSoapObject(request);
			//Creaccion del transporte
			HttpTransportSE transporte = new HttpTransportSE(URL);
			//Llamada
			transporte.call(SOAP_ACTION, sobre);
			//Resultado
			SoapObject resultsRequestSOAP = (SoapObject)sobre.bodyIn;
			res = Boolean.parseBoolean(resultsRequestSOAP.getProperty(0).toString());
        }catch (Exception e) 
        {
        	res=false;
        }
		return res;
	}
	
	public static boolean eliminarUsuario(long id)
	{
        setCall(3);
        boolean res;
		try 
		{
	       //Creaccion de la Solicitud
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			request.addProperty("id",id);
			//Creaccion del Envelope
			SoapSerializationEnvelope sobre = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			sobre.dotNet = false;
			sobre.setOutputSoapObject(request);
			//Creaccion del transporte
			HttpTransportSE transporte = new HttpTransportSE(URL);
			//Llamada
			transporte.call(SOAP_ACTION, sobre);
			//Resultado
			SoapObject resultsRequestSOAP = (SoapObject)sobre.bodyIn;
			res = Boolean.parseBoolean(resultsRequestSOAP.getProperty(0).toString());
        }catch (Exception e) 
        {
        	res=false;
        }
		return res;
	}	
	
	public static boolean actualizarUsuario(long id, String nombre, String apellido, String email, 
			String pass, String tipo, int numero, int radio)
	{
        setCall(4);
        boolean res;
		try 
		{
	       //Creaccion de la Solicitud
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			request.addProperty("id",id);
			request.addProperty("nombre",nombre);
			request.addProperty("apellido",apellido);
			request.addProperty("email",email);
			request.addProperty("pass",md5(pass));
			request.addProperty("numeroSucursal",numero);
			request.addProperty("tipo",tipo);
			request.addProperty("radio",radio);
			//Creaccion del Envelope
			SoapSerializationEnvelope sobre = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			sobre.dotNet = false;
			sobre.setOutputSoapObject(request);
			//Creaccion del transporte
			HttpTransportSE transporte = new HttpTransportSE(URL);
			//Llamada
			transporte.call(SOAP_ACTION, sobre);
			//Resultado
			SoapObject resultsRequestSOAP = (SoapObject)sobre.bodyIn;
			res = Boolean.parseBoolean(resultsRequestSOAP.getProperty(0).toString());
        }catch (Exception e) 
        {
        	res=false;
        }
		return res;
	}
	
	public static boolean actualizarPass(long id, String pass)
	{
        setCall(5);
        boolean res;
		try 
		{
	       //Creaccion de la Solicitud
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			request.addProperty("id",id);
			request.addProperty("pass",md5(pass));
			//Creaccion del Envelope
			SoapSerializationEnvelope sobre = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			sobre.dotNet = false;
			sobre.setOutputSoapObject(request);
			//Creaccion del transporte
			HttpTransportSE transporte = new HttpTransportSE(URL);
			//Llamada
			transporte.call(SOAP_ACTION, sobre);
			//Resultado
			SoapObject resultsRequestSOAP = (SoapObject)sobre.bodyIn;
			res = Boolean.parseBoolean(resultsRequestSOAP.getProperty(0).toString());
        }catch (Exception e) 
        {
        	res=false;
        }
		return res;
	}
	
	public static List<Usuario> listarUsuarioEmpresa(){
        setCall(8);
        List<Usuario> us=new ArrayList<Usuario>();
		try 
		{
	       //Creaccion de la Solicitud
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			//Creaccion del Envelope
			SoapSerializationEnvelope sobre = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			sobre.dotNet = false;
			sobre.setOutputSoapObject(request);
			//Creaccion del transporte
			HttpTransportSE transporte = new HttpTransportSE(URL);
			//Llamada
			transporte.call(SOAP_ACTION, sobre);
			//Resultado
			SoapObject resultsRequestSOAP = (SoapObject)sobre.bodyIn;
			us=new ArrayList<Usuario>();
			Usuario u;
			for(int i=0;i<resultsRequestSOAP.getPropertyCount();i++){
				SoapObject object=(SoapObject) resultsRequestSOAP.getProperty(i);
				u=makeUsuario(object);
				us.add(u);
			}	
        }catch (Exception e) 
        {
        	us=null;
        }
		return us;
	}
}
